﻿using log4net.Core;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public class DbContext
    {
        public static SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
        {
            ConnectionString =
            "Data Source=localhost;Initial Catalog=mianshi;Persist Security Info=True;User ID=sa;Password=1234",//连接符字串
            DbType = SqlSugar.DbType.SqlServer, //数据库类型
            IsAutoCloseConnection = true, //不设成true要手动close
            ConfigureExternalServices = new ConfigureExternalServices()
            {
                EntityService = (x, p) => //处理列名
                {
                    p.DbColumnName = UtilMethods.ToUnderLine(p.DbColumnName);//ToUnderLine驼峰转下划线方法
                },
                EntityNameService = (x, p) => //处理表名
                {
                    //最好排除DTO类
                    p.DbTableName = UtilMethods.ToUnderLine(p.DbTableName);//ToUnderLine驼峰转下划线方法
                }
            }
        }, db =>
        {
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                //Console.WriteLine(sql);//输出sql

                Console.WriteLine("\r\n");
                Console.WriteLine($"{DateTime.Now:yyyyMMdd HH:mm:ss}"+UtilMethods.GetNativeSql(sql, pars));

            };
            db.Aop.OnError = (exp) =>
            {
                Console.WriteLine("\r\n");
                Console.WriteLine($"错误sql:{exp.Sql}");
                //Console.WriteLine($"错误参数:{exp.Parametres}");
            };
        });
        public static void InitDataBase()
        {
            //初始化数据库:如果不存在则创建数据库
            db.DbMaintenance.CreateDatabase();
            //创建表
            string nspace = "Model.Entitys";
            Type[] ass = Assembly.LoadFrom("bin/Debug/net6.0/Model.dll").GetTypes().Where(p => p.Namespace == nspace).ToArray();
            db.CodeFirst.SetStringDefaultLength(255).InitTables(ass);
        }
        public static void InitEntitys()
        {
            db.DbFirst.IsCreateAttribute()
                .CreateClassFile("D:\\visualstudio_workspace\\SysWebApi\\Model\\Entitys", "Model.Entitys");
        }

    }
}
